<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入任务名称" clearable style="width: 240px" />
      </el-form-item>
      <el-form-item label="自动刷新频率" label-width="100px">
        <el-select v-model="frequency" placeholder="请选择刷新频率" style="width: 120px" @change="handleRefresh">
          <el-option v-for="item in frequency_options" :key="item" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
        <el-button icon="refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="danger" plain icon="delete" :disabled="multiple" @click="handleDelete"
          v-hasFunc="'schedule:del'">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="plus" @click="handleAdd" v-hasFunc="'schedule:add'">添加任务</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="edit" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col> -->

      <right-toolbar :showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
      <!-- <div>
        刷新时间
        <IconPlus name="bug" />
      </div> -->
    </el-row>

    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange" highlight-current-row>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务编码" align="center" prop="id" :show-overflow-tooltip="true"
        v-if="columns.showColumn('id')">
        <template #default="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="任务名称" align="center" prop="name" :show-overflow-tooltip="true"
        v-if="columns.showColumn('name')">
        <template #default="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="任务描述" align="center" prop="description" :show-overflow-tooltip="true"
        v-if="columns.showColumn('description')">
        <template #default="scope">
          {{ scope.row.description }}
        </template>
      </el-table-column> -->
      <el-table-column label="任务类型" align="center" prop="extend.type" :show-overflow-tooltip="true"
        v-if="columns.showColumn('extend.type')">
        <template #default="{ row }">
          <dict-tag :options="job_type" :value="row.extend.type" />
        </template>
      </el-table-column>
      <el-table-column label="触发模式" align="center" prop="extend.type" :show-overflow-tooltip="true"
        v-if="columns.showColumn('extend.type')">
        <template #default="{ row }">
          <dict-tag :options="trigger_type" :value="row.trigger.type" />
        </template>
      </el-table-column>
      <el-table-column label="最近一次" align="center" prop="nextFireTime" :show-overflow-tooltip="true"
        v-if="columns.showColumn('nextFireTime')">
        <template #default="{ row }">
          {{ parseTime(row.lastFireTime) }}
        </template>
      </el-table-column>
      <el-table-column label="下次计划" align="center" prop="nextFireTime" :show-overflow-tooltip="true"
        v-if="columns.showColumn('nextFireTime')">
        <template #default="{ row }">
          {{ parseTime(row.nextFireTime) }}
        </template>
      </el-table-column>
      <el-table-column label="已调度（次）" align="center" prop="fireCount" :show-overflow-tooltip="true"
        v-if="columns.showColumn('fireCount')">
        <template #default="{ row }">
          {{ row.fireCount }}
        </template>
      </el-table-column>
      <el-table-column label="有效期至" align="center" prop="trigger.effictEndTime" :show-overflow-tooltip="true"
        v-if="columns.showColumn('trigger.effictEndTime')">
        <template #default="{ row }">
          {{ row.trigger.forever ? '永久' : parseTime(row.trigger.effictEndTime) }}
        </template>
      </el-table-column>
      <el-table-column label="任务状态" align="center" prop="status" :show-overflow-tooltip="true"
        v-if="columns.showColumn('status')">
        <template #default="{ row }">
          <dict-tag :options="scheduler_status" :value="row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template #default="{ row }">
          <el-button v-show="row.status == 0" type="primary" text icon="VideoPlay" v-hasFunc="'schedule:startup'"
            @click="handleStartup(row)">启动</el-button>
          <el-button v-show="row.status == 1" type="primary" text icon="VideoPause" v-hasFunc="'schedule:pause'"
            @click="handlePause(row)">暂停</el-button>
          <el-button v-show="row.status == 3" type="primary" text icon="VideoPlay" v-hasFunc="'schedule:resume'"
            @click="handleResume(row)">继续</el-button>
          <el-button type="primary" text icon="delete" @click="handleDelete(row)"
            v-hasFunc="'schedule:del'">删除</el-button>

          <el-dropdown @command="handleCommand($event, row)">
            <el-button style="margin-left: 10px;" text type="primary" icon="more">更多</el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <div v-hasFunc="'schedule:once'">
                  <el-dropdown-item command="handleOnce">
                    <IconPlus name="trigger"></IconPlus>
                    执行一次
                  </el-dropdown-item>
                </div>
                <div><el-dropdown-item command="handleView" icon="view">任务详情</el-dropdown-item></div>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <!-- <el-button type="primary" text icon="view" @click="handleView(scope.row)">查看</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageIndex"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
    <NewJob ref="newJobRef" @scheduled="getList" />

    <!-- 任务明细展示 -->
    <el-drawer v-model="detailOpen" width="500px">
      <el-descriptions title="基本信息" :column="1" border label-width="100px" style="margin-bottom: 30px;">
        <el-descriptions-item label="任务编码">
          {{ form.id }}
        </el-descriptions-item>
        <el-descriptions-item label="任务名称">{{ form.name }}</el-descriptions-item>
        <el-descriptions-item label="任务类型">
          <dict-tag :options="job_type" :value="form.extend.type" />
        </el-descriptions-item>
        <template v-if="form.extend.type == 0">
          <el-descriptions-item label="远程地址">{{ form.extend.remote }}</el-descriptions-item>
          <el-descriptions-item label="请求方式">{{ form.extend.method }}</el-descriptions-item>
          <el-descriptions-item label="请求参数">{{ form.extend.params }}</el-descriptions-item>
        </template>
        <template v-if="form.extend.type == 1">
          <el-descriptions-item label="执行程序">{{ form.extend.jobType }}</el-descriptions-item>
        </template>
        <el-descriptions-item label="有效期至">
          {{ form.trigger.forever ? '永久' : parseTime(form.trigger.effictEndTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="任务状态">
          <dict-tag :options="scheduler_status" :value="form.status" />
        </el-descriptions-item>
        <el-descriptions-item label="最近一次"> {{ parseTime(form.lastFireTime) }} </el-descriptions-item>
        <el-descriptions-item label="下次计划"> {{ parseTime(form.nextFireTime) }} </el-descriptions-item>
        <el-descriptions-item label="已调度（次）"> {{ form.fireCount }} </el-descriptions-item>
        <el-descriptions-item label="触发模式">
          <dict-tag :options="trigger_type" :value="form.trigger.type" />
        </el-descriptions-item>
        <template v-if="form.trigger.type == 'simple'">
          <el-descriptions-item label="执行间隔(s)"> {{ form.trigger.interval }} </el-descriptions-item>
          <el-descriptions-item label="执行次数(s)"> {{ form.trigger.repeat }} </el-descriptions-item>
        </template>
        <template v-if="form.trigger.type == 'cron'">
          <el-descriptions-item label="表达式(Cron)"> {{ form.trigger.cron }} </el-descriptions-item>
        </template>
        <el-descriptions-item label="任务描述" style="word-break: break-all;">{{ form.description }} </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailOpen = false" type="primary">关闭</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { job_type, trigger_type, scheduler_status, frequency_options } from './status.js';
import { ref, reactive, onMounted } from "vue";
import { listScheduledJob, getScheduledJob, delScheduledJob, updateScheduledJob, pauseJob, resumeJob, startupJob, triggerOnce } from "@/api/schedule/scheduledjob.js";
import NewJob from './NewJob.vue';
const { proxy } = getCurrentInstance()

// 遮罩层
const loading = ref(true);
// 选中数组
const selected = ref([]);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 数据集
const dataList = ref([]);
const newJobRef = ref();

//刷新频率
const frequency = ref(5);



// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);

//明细展示
const detailOpen = ref(false);

//默认时间范围
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])
// 查询参数
const queryParams = reactive({
  pageIndex: 1,
  pageSize: 10,
  name: undefined
});



const state = reactive({
  single: true,
  multiple: true,
  form: {
    trigger: {
      type: 'simple',
    },
    extend: {
      type: 0,
      params: [{ key: undefined, value: undefined }],
    }
  },
  rules: {
    //customerId: [{ required: true, message: "客户id不能为空", trigger: "blur"    , type: "number"  }],
    //name: [{ required: true, message: "商品名称不能为空", trigger: "blur"     }],
  },
  options: {
    // 商品种类 选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
    typeOptions: [],
  }
})

const { form, rules, options, single, multiple } = toRefs(state)


//所有列
const columns = ref([
  { visible: true, prop: 'id', label: '任务编码' },
  { visible: true, prop: 'name', label: '任务名称' },
  { visible: true, prop: 'description', label: '任务描述' },
  { visible: true, prop: 'extend.type', label: '任务类型' },
  { visible: true, prop: 'isActive', label: '状态' },
]);

// 获取列表方法
const getList = () => {
  loading.value = true;
  return listScheduledJob(queryParams).then((response) => {
    dataList.value = response.result;
    total.value = response.totalNum;
    loading.value = false;
  });
};

// 重置表单
const reset = () => {

};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageIndex = 1;
  getList();
};

// 重置按钮操作
const resetQuery = () => {
  reset();
  handleQuery();
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
  selected.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

// 新增按钮操作
const handleAdd = () => {
  newJobRef.value.show();
};

// 修改按钮操作
const handleUpdate = (row) => {
  reset();
  const key = row.id || selected.value;
  getScheduledJob(key).then((response) => {
    Object.assign(form.value, response);
    open.value = true;
    title.value = "修改数据";
  });
};


//查看
const handleView = (row) => {
  reset();
  var key = row.id;
  getScheduledJob(key).then((response) => {
    Object.assign(form.value, response);
    detailOpen.value = true;
    title.value = "查看明细";
  });
}


// 删除按钮操作
const handleDelete = (row) => {
  const keys = [].concat(row.id || selected.value);
  proxy.$modal.confirm("是否确认删除编号为" + keys + "的数据项？")
    .then(() => delScheduledJob(keys))
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
};

//暂停任务
const handlePause = (row) => {
  pauseJob(row.id).then(() => {
    proxy.$modal.msgSuccess("暂停成功");
    return getList();
  })
}

//恢复任务
const handleResume = (row) => {
  resumeJob(row.id).then(() => {
    proxy.$modal.msgSuccess("恢复成功");
    return getList();
  })
}

//启动任务
const handleStartup = (row) => {
  startupJob(row.id).then(() => {
    proxy.$modal.msgSuccess("启动成功");
    return getList();
  })
}

//额外执行一次任务
const handleOnce = (row) => {
  triggerOnce(row.id).then(() => {
    proxy.$modal.msgSuccess("操作成功");
    return getList();
  })
}

//下拉菜单命令集
const handleCommand = (cmd, row) => {
  switch (cmd) {
    case 'handleView':
      handleView(row)
      break;
    case 'handlePause':
      handlePause(row);
      break;
    case 'handleResume':
      handleResume(row);
      break;
    case 'handleOnce':
      handleOnce(row);
      break;
    default:
      break;
  }
}

let intervalId;

//刷新
const refresh = () => {
  return listScheduledJob(queryParams).then((response) => {
    dataList.value = response.result;
    total.value = response.totalNum;
  });
}
//自动刷新
const handleRefresh = (value) => {
  // 清除之前的定时器
  if (intervalId) {
    clearInterval(intervalId);
  }
  if (value > 0) {
    // 设置新的定时器
    intervalId = setInterval(refresh, value * 1000);
  }
};

// 页面加载时调用获取列表方法
onMounted(() => {
  getList();
  handleRefresh(5);
});


onUnmounted(() => {
  // 组件卸载时清除定时器
  if (intervalId) {
    clearInterval(intervalId);
  }
});
</script>

<style lang="scss" scoped>
.params-wrapper {
  display: flex;
  flex-direction: column;
  flex: 1;

  .params-item {
    padding-bottom: 15px;
    display: flex;
    gap: 10px;
    flex: 1;



    >div {
      display: flex;
      gap: 10px;
    }


    .action {
      flex-grow: 0;
      gap: 0;
      margin-left: auto;
    }
  }
}

.footer {
  display: flex;

  .step {
    flex: 1;
  }

  .action {
    margin-left: auto;
  }
}
</style>
